package top.shiyiri.community.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import top.shiyiri.community.service.AlphaService;
import top.shiyiri.community.util.CommunityUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * @author Aunean
 * @date 2022/3/13 11:26
 */
@Controller
@RequestMapping("/alpha")
public class AlphaController {

    //方式一：变量注入
    @Autowired
    private AlphaService alphaService;

    //方式二：set方法注入
//    private AlphaService alphaService;
//    @Autowired
//    public void setAlphaService(AlphaService alphaService) {
//        this.alphaService = alphaService;
//    }

    //方式三：构造方法注入
//    private AlphaService alphaService;
//    @Autowired
//    public void AlphaService(AlphaService alphaService) {
//        this.alphaService = alphaService;
//    }

    @GetMapping("/data")
    @ResponseBody
    public String index() {
        return alphaService.getAlphaDao();
    }

    @GetMapping("/http")
    @ResponseBody
    public void http(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取请求数据
        System.out.println("请求方式：" + request.getMethod());
        System.out.println("请求路径：" + request.getServletPath());
        //请求行
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = request.getHeader(name);
            System.out.println(name + ":" + value);
        }
        System.out.println("code：" + request.getParameter("code"));
        response.setContentType("text/html;charset=utf-8");
        //返回响应数据
        response.getWriter().write("<h1>一级标题</h1>");
    }

    /*
        /students?current=1&limit=20
     */
    @RequestMapping(value = "/students", method = RequestMethod.GET)
    @ResponseBody
    public String getStudents(@RequestParam(value = "current", required = false, defaultValue = "1") int current,
                              @RequestParam(value = "limit", required = false, defaultValue = "20") int limit) {
        System.out.println("current：" + current + ", limit：" + limit);
        return "some students";
    }

    /*
        /student/123
     */
    @RequestMapping(value = "/student/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudent(@PathVariable("id") int id) {
        System.out.println("id：" + id);
        return "a student";
    }

    @PostMapping("/student")
    @ResponseBody
    public String saveStudent(String name, Integer age) {
        return "name：" + name + "，age：" + age;
    }

    /*
        响应HTML数据
     */
    @RequestMapping(value = "/teacher", method = RequestMethod.GET)
    public ModelAndView getTeacher() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("name", "张三");
        modelAndView.addObject("age", 45);
        modelAndView.setViewName("/demo/view");
        return modelAndView;
    }

    @RequestMapping(value = "/school", method = RequestMethod.GET)
    public String getSchool(Model model) {
        model.addAttribute("name", "小学");
        model.addAttribute("age", 100);
        return "/demo/view";
    }

    //响应JSON数据（异步请求）
    @RequestMapping(value = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 23);
        map.put("salary", 5002.4);
        return map;
    }

    //响应JSON数据（异步请求）
    @RequestMapping(value = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 23);
        map.put("salary", 5002.4);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "李四");
        map2.put("age", 34);
        map2.put("salary", 15002.4);
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map);
        list.add(map2);
        return list;
    }

    /**
     * Cookie示例
     */
    @GetMapping("/cookie/set")
    @ResponseBody
    public String setCookie(HttpServletResponse response) {
        //创建 cookie
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        //设置 cookie 生效的范围
        cookie.setPath("/community/alpha");
        // 设置 cookie 的生存时间
        cookie.setMaxAge(60 * 10);
        // 发送 cookie
        response.addCookie(cookie);
        return "set cookie";
    }

    @GetMapping("/cookie/get")
    @ResponseBody
    public String getCookie(@CookieValue("code") String code) {
        return code;
    }

    /**
     * Session 示例
     */
    @GetMapping("/session/set")
    @ResponseBody
    public String setSession(HttpSession session) {
        session.setAttribute("id", 1);
        session.setAttribute("name", "Test");
        return "set session";
    }

    @GetMapping("/session/get")
    @ResponseBody
    public String getSession(HttpSession session) {
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session";
    }

    /**
     * ajax示例
     */
    @PostMapping("/ajax")
    @ResponseBody
    public String testAjax(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return CommunityUtil.getJSONString(0, "操作成功");
    }

}
